import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

typedef VoidCallback = void Function();

class CustomRefresher extends StatelessWidget {
  const CustomRefresher({
    required this.controller,
    this.enablePullDown = true,
    this.enablePullUp = false,
    this.onLoading,
    this.onRefresh,
    this.child,
    super.key,
  });
  // 是否允许刷新
  final bool enablePullDown;
  // 是否允许加载
  final bool enablePullUp;
  // 控制器
  final RefreshController controller;

  // 下拉刷新回调
  final VoidCallback? onRefresh;

  // 上拉加载回调
  final VoidCallback? onLoading;

  // 可滚动子组件
  final Widget? child;

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: controller,
      enablePullDown: enablePullDown, // 允许刷新
      enablePullUp: enablePullUp, // 允许上拉加载
      onRefresh: onRefresh,
      onLoading: onLoading,
      // header: WaterDropHeader(), // 下拉展示样式组件 水滴组件
      header: CustomHeader(
        builder: (context, mode) {
          //下拉状态文字
          String refreshText = '下拉刷新';
          String refreshIcon = 'assets/refresh.png';

          // 空闲状态
          if (mode == RefreshStatus.idle) {
            refreshText = '下拉刷新';
          }
          if (mode == RefreshStatus.canRefresh) {
            refreshText = '释放刷新';
          }
          if (mode == RefreshStatus.refreshing) {
            refreshText = '正在刷新';
            refreshIcon = 'assets/refresh.gif';
          }
          if (mode == RefreshStatus.completed) {
            refreshText = '刷新完成';
          }
          if (mode == RefreshStatus.failed) {
            refreshText = '刷新失败';
          }
          return Container(
            alignment: Alignment.center,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Image.asset(refreshIcon, width: 30, height: 30),
                Text(refreshText),
              ],
            ),
          );
        },
      ),
      footer: CustomFooter(
        builder: (context, mode) {
          // 上拉状态文字
          Widget body = Text('上拉加载更多');
          // 空闲状态
          if (mode == LoadStatus.idle) {
            body = Text('上拉加载更多');
          }

          if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          }

          if (mode == LoadStatus.failed) {
            body = Text('加载失败,下拉重试');
          }
          if (mode == LoadStatus.noMore) {
            body = Text('-----无数据,我们是有底线的-----');
          }

          return Container(
            alignment: Alignment.center,
            height: 55,
            child: Center(child: body),
          );
        },
      ),
      child: child,
    );
  }
}
